<template>
  <div 
    class="file-drag-drop-handler"
    :class="{ 
      'drag-active': isDragActive,
      'drag-over': isDragOver 
    }"
    @dragenter="handleDragEnter"
    @dragover="handleDragOver"
    @dragleave="handleDragLeave"
    @drop="handleDrop"
  >
    <!-- 拖拽提示遮罩 -->
    <div v-if="isDragActive" class="drag-overlay">
      <div class="drag-content">
        <el-icon class="drag-icon">
          <Upload />
        </el-icon>
        <h3>释放文件开始上传</h3>
        <p>支持多文件同时上传</p>
      </div>
    </div>

    <!-- 子组件内容 -->
    <slot />

    <!-- 上传进度提示 -->
    <el-dialog
      v-model="showUploadDialog"
      title="文件上传"
      width="500px"
      :close-on-click-modal="false"
    >
      <div class="upload-progress">
        <div v-for="file in uploadingFiles" :key="file.name" class="upload-item">
          <div class="file-info">
            <el-icon class="file-icon">
              <Document />
            </el-icon>
            <div class="file-details">
              <div class="file-name">{{ file.name }}</div>
              <div class="file-size">{{ formatFileSize(file.size) }}</div>
            </div>
          </div>
          <div class="progress-info">
            <el-progress 
              :percentage="file.progress" 
              :status="file.status"
              :stroke-width="6"
            />
            <div class="progress-text">
              {{ file.status === 'success' ? '上传完成' : 
                 file.status === 'exception' ? '上传失败' : 
                 `${file.progress}%` }}
            </div>
          </div>
        </div>
      </div>
      
      <template #footer>
        <el-button @click="closeUploadDialog">关闭</el-button>
        <el-button type="primary" @click="closeUploadDialog" v-if="allUploadsComplete">
          完成
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Upload, Document } from '@element-plus/icons-vue'
import { useFileUpload } from '@/composables/useFileUpload'

// Props
interface Props {
  disabled?: boolean
  acceptTypes?: string[]
  maxFileSize?: number // MB
  targetFolderId?: number
}

const props = withDefaults(defineProps<Props>(), {
  disabled: false,
  acceptTypes: () => [],
  maxFileSize: 100,
  targetFolderId: undefined
})

// Emits
const emit = defineEmits<{
  filesDropped: [files: File[]]
  uploadStarted: [files: File[]]
  uploadCompleted: [results: any[]]
}>()

// 状态管理
const isDragActive = ref(false)
const isDragOver = ref(false)
const dragCounter = ref(0)
const showUploadDialog = ref(false)
const uploadingFiles = ref<Array<{
  name: string
  size: number
  progress: number
  status: 'normal' | 'success' | 'exception'
}>>([])

// 文件上传组合式函数
const { uploadFiles } = useFileUpload()

// 检测是否为Electron环境
const isElectron = !!(window as any).electronAPI

// 计算属性
const allUploadsComplete = computed(() => {
  return uploadingFiles.value.length > 0 && 
         uploadingFiles.value.every(file => 
           file.status === 'success' || file.status === 'exception'
         )
})

// 格式化文件大小
const formatFileSize = (bytes: number): string => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 验证文件类型
const validateFileType = (file: File): boolean => {
  if (props.acceptTypes.length === 0) return true
  
  const fileExtension = file.name.split('.').pop()?.toLowerCase()
  const mimeType = file.type.toLowerCase()
  
  return props.acceptTypes.some(type => {
    if (type.startsWith('.')) {
      return fileExtension === type.slice(1)
    }
    if (type.includes('/')) {
      return mimeType.includes(type)
    }
    return false
  })
}

// 验证文件大小
const validateFileSize = (file: File): boolean => {
  const maxBytes = props.maxFileSize * 1024 * 1024
  return file.size <= maxBytes
}

// 拖拽事件处理
const handleDragEnter = (e: DragEvent) => {
  e.preventDefault()
  e.stopPropagation()
  
  if (props.disabled) return
  
  dragCounter.value++
  if (dragCounter.value === 1) {
    isDragActive.value = true
  }
}

const handleDragOver = (e: DragEvent) => {
  e.preventDefault()
  e.stopPropagation()
  
  if (props.disabled) return
  
  isDragOver.value = true
  
  // 设置拖拽效果
  if (e.dataTransfer) {
    e.dataTransfer.dropEffect = 'copy'
  }
}

const handleDragLeave = (e: DragEvent) => {
  e.preventDefault()
  e.stopPropagation()
  
  dragCounter.value--
  if (dragCounter.value === 0) {
    isDragActive.value = false
    isDragOver.value = false
  }
}

const handleDrop = async (e: DragEvent) => {
  e.preventDefault()
  e.stopPropagation()
  
  // 重置拖拽状态
  isDragActive.value = false
  isDragOver.value = false
  dragCounter.value = 0
  
  if (props.disabled) return
  
  const files = Array.from(e.dataTransfer?.files || [])
  
  if (files.length === 0) {
    ElMessage.warning('没有检测到文件')
    return
  }
  
  // 验证文件
  const validFiles: File[] = []
  const invalidFiles: string[] = []
  
  files.forEach(file => {
    if (!validateFileType(file)) {
      invalidFiles.push(`${file.name}: 不支持的文件类型`)
      return
    }
    
    if (!validateFileSize(file)) {
      invalidFiles.push(`${file.name}: 文件大小超过${props.maxFileSize}MB`)
      return
    }
    
    validFiles.push(file)
  })
  
  // 显示验证错误
  if (invalidFiles.length > 0) {
    ElMessage.error(`以下文件无法上传：\n${invalidFiles.join('\n')}`)
  }
  
  if (validFiles.length === 0) return
  
  // 触发事件
  emit('filesDropped', validFiles)
  
  // 开始上传
  await startUpload(validFiles)
}

// 开始上传文件
const startUpload = async (files: File[]) => {
  // 初始化上传状态
  uploadingFiles.value = files.map(file => ({
    name: file.name,
    size: file.size,
    progress: 0,
    status: 'normal' as const
  }))
  
  showUploadDialog.value = true
  emit('uploadStarted', files)
  
  try {
    // 模拟上传进度（实际项目中应该使用真实的上传逻辑）
    const uploadPromises = files.map(async (file, index) => {
      const uploadItem = uploadingFiles.value[index]
      
      try {
        // 模拟上传进度
        for (let progress = 0; progress <= 100; progress += 10) {
          uploadItem.progress = progress
          await new Promise(resolve => setTimeout(resolve, 100))
        }
        
        uploadItem.status = 'success'
        return { file, success: true }
      } catch (error) {
        uploadItem.status = 'exception'
        return { file, success: false, error }
      }
    })
    
    const results = await Promise.all(uploadPromises)
    emit('uploadCompleted', results)
    
    const successCount = results.filter(r => r.success).length
    ElMessage.success(`成功上传 ${successCount} 个文件`)
    
  } catch (error) {
    ElMessage.error('上传过程中发生错误')
    console.error('Upload error:', error)
  }
}

// 关闭上传对话框
const closeUploadDialog = () => {
  showUploadDialog.value = false
  uploadingFiles.value = []
}

// 启用Electron拖拽支持
const enableElectronDragDrop = () => {
  if (!isElectron) return
  
  const electronAPI = (window as any).electronAPI
  if (electronAPI?.drag?.enableFileDrop) {
    electronAPI.drag.enableFileDrop((files: string[]) => {
      console.log('Electron文件拖拽:', files)
      // 这里可以处理Electron特有的文件路径
    })
  }
}

// 组件挂载时启用拖拽支持
onMounted(() => {
  enableElectronDragDrop()
})

// 组件卸载时清理
onUnmounted(() => {
  // 清理拖拽状态
  isDragActive.value = false
  isDragOver.value = false
  dragCounter.value = 0
})
</script>

<style scoped>
.file-drag-drop-handler {
  position: relative;
  width: 100%;
  height: 100%;
  min-height: 200px;
}

.drag-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(64, 158, 255, 0.1);
  backdrop-filter: blur(4px);
  z-index: 9999;
  display: flex;
  align-items: center;
  justify-content: center;
  pointer-events: none;
}

.drag-content {
  text-align: center;
  padding: 40px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  border: 2px dashed #409EFF;
}

.drag-icon {
  font-size: 48px;
  color: #409EFF;
  margin-bottom: 16px;
}

.drag-content h3 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 18px;
}

.drag-content p {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.upload-progress {
  max-height: 400px;
  overflow-y: auto;
}

.upload-item {
  display: flex;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #EBEEF5;
}

.upload-item:last-child {
  border-bottom: none;
}

.file-info {
  display: flex;
  align-items: center;
  flex: 1;
  margin-right: 16px;
}

.file-icon {
  font-size: 24px;
  color: #409EFF;
  margin-right: 12px;
}

.file-details {
  flex: 1;
}

.file-name {
  font-weight: 500;
  color: #303133;
  margin-bottom: 4px;
  word-break: break-all;
}

.file-size {
  font-size: 12px;
  color: #909399;
}

.progress-info {
  width: 200px;
}

.progress-text {
  text-align: center;
  font-size: 12px;
  color: #606266;
  margin-top: 4px;
}

/* 拖拽激活状态 */
.drag-active {
  position: relative;
}

.drag-active::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  border: 2px dashed #409EFF;
  border-radius: 8px;
  background: rgba(64, 158, 255, 0.05);
  pointer-events: none;
  z-index: 1;
}
</style>
